<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/xmlfeed.php";

if ($loadsubpage == 1)
{
  $slid = isset ($_GET['slid']) ? $_GET['slid'] : 0;
  $tid = isset ($_GET['tid']) ? $_GET['tid'] : 0;
  
  /* Get site name */
  $result = mysql_query ("SELECT sitename, domainname, protocol FROM ".db_maketablename ($table_settings)." LIMIT 1");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      $sitename = htmlentities ($row['sitename'], ENT_COMPAT, "UTF-8", false);
      $domainname = htmlentities ($row['domainname'], ENT_COMPAT, "UTF-8", false);
      $protocol = $row['protocol'] != "" ? $row['protocol'] : "http";
    }
  mysql_free_result ($result);
?>
<h1>
  <?=$sitename?>
  <a href="<?=$protocol?>://<?=$domainname?>/" title="Go to website" rel="external"><img src="./images/link.gif" alt="CodeMirror" class="externallink" /></a>
</h1>

<div id="templates">
  <h3>Templates</h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_templates)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $name = htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl";
        print "<tr><td><a href=\"./?p=templates&amp;tid={$row['id']}\"><strong>$name</strong></a></td>";
        print "<td class=\"alignright\"><a href=\"javascript:deltemplate('$name', {$row['id']});\" title=\"Delete '$name'\"><strong>&times;</strong></a></td></tr>\n";
      }
  }
mysql_free_result ($result);
?>
  </table>

  <div id="addnew1">
    <p>
      <input type="button" value="+" onclick="document.getElementById('addnew2').style.display='block';" class="button" />
      Add new template
    </p>
  </div>

  <div id="addnew2">
    <form action="../includes/addtemplate.php" method="post">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td><strong>Name:</strong>&nbsp;</td>
          <td><input type="text" name="name" value="Type_name_here" maxlength="50" class="textfield" />.xsl</td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Add &raquo;" class="button" /></td>
        </tr>
      </table>
    </form>
  </div>
  
  <div id="separator">&nbsp;</div>

  <h3>Sublayouts</h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_sublayouts)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $name = htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl";
        print "<tr><td><a href=\"./?p=templates&amp;slid={$row['id']}\"><strong>$name</strong></a></td>";
        print "<td class=\"alignright\"><a href=\"javascript:delsublayout('$name', {$row['id']});\" title=\"Delete '$name'\"><strong>&times;</strong></a></td></tr>\n";
      }
  }
mysql_free_result ($result);
?>
  </table>

  <div id="addnew3">
    <p>
      <input type="button" value="+" onclick="document.getElementById('addnew4').style.display='block';" class="button" />
      Add new sublayout
    </p>
  </div>

  <div id="addnew4">
    <form action="../includes/addsublayout.php" method="post">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td><strong>Name:</strong>&nbsp;</td>
          <td><input type="text" name="name" value="Type_name_here" maxlength="50" class="textfield" />.xsl</td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Add &raquo;" class="button" /></td>
        </tr>
      </table>
    </form>
  </div>
</div>

<div id="editor">
<?php
/* If no template is selected... */
if (empty ($tid) && empty ($slid))
{
?>
  <div id="info">
    <p>&larr; Click on an item in the list to edit it.</p>
  </div>
<?php
}
else
{
?>
    <div id="tabs">
      <ul>
<?php
if (!empty ($tid) && empty ($slid))
{
?>
        <li><a href="javascript:switchtabs ('tab1');">Template</a></li>
        <li><a href="javascript:switchtabs ('tab2');">Parameters</a></li>
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
        <li><span>Sublayout</span></li>
<?php
}
?>
      </ul>
    </div>
    
<?php
if (!empty ($tid) && empty ($slid))
{
?>
    <form action="../includes/savetemplate.php" method="post">
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
    <form action="../includes/savesublayout.php" method="post">
<?php
}
?>
<?php
if (!empty ($tid) && empty ($slid))
{
?>
      <div id="tab1">
<?php
  $result = mysql_query ("SELECT name, fields, xslt FROM ".db_maketablename ($table_templates)." WHERE id='$tid'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      $layout = htmlentities ($row['xslt'], ENT_COMPAT, "UTF-8", true);
      
      /* Parse fields and xmlfeed */
      print "<label>Name</label><br /><input type=\"text\" name=\"templatename\" value=\"".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false)."\" class=\"textfield\" />\n";
      
      /* Prepare the XML parser and parse the data */
      $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
      $xmlres = xml_parser_create ("utf-8");
      xml_parse_into_struct ($xmlres, $xmldata, $values);
      xml_parser_free ($xmlres);
?>
        <table cellpadding="0" cellspacing="0">
          <thead>
            <td class="col1"><label>Field name</label></td>
            <td class="col2"><label>Label</label></td>
            <td class="col3"><label>Type</label></td>
            <td class="col4">&nbsp;</td>
          </thead>
<?php
      /* Walk through the tags */
      $i = 0;
      $fieldcount = 0;
      while (!empty ($values[$i]))
        {
          if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']) && isset ($values[$i]['attributes']['LABEL']) && isset ($values[$i]['attributes']['TYPE']))
            {
              $fieldcount++;
              print "<tr>";
              print "<td class=\"col1\"><input type=\"text\" name=\"name$fieldcount\" value=\"{$values[$i]['attributes']['NAME']}\" class=\"smalltextfield\" /></td>";
              print "<td class=\"col2\"><input type=\"text\" name=\"label$fieldcount\" value=\"{$values[$i]['attributes']['LABEL']}\" class=\"smalltextfield\" /></td>";
              print "<td class=\"col3\"><select name=\"type$fieldcount\">";
              foreach ($fieldtypes as $type)
                {
                  $sel = $values[$i]['attributes']['TYPE'] == $type ? " selected=\"selected\"" : "";
                  print "<option value=\"$type\"$sel>$type</option>";
                }
              print "</select></td>";
              print "<td><input type=\"submit\" name=\"delfield$fieldcount\" value=\"-\" class=\"alignright\" /></td>";
              print "</tr>\n";
            }
          $i++;
        }
?>
        </table>
        
        <p>
          <input type="submit" name="addfield" value="+" />
          <span class="addfield">Add new field</span>
        </p>
        
        <label>Layout</label>
        <textarea id="xslt" name="templatelayout"><?=$layout?></textarea>
        <script type="text/javascript">
          //<![CDATA[
            var editor = CodeMirror.fromTextArea (document.getElementById ("xslt"), { mode: { name: "xmlpure" } });
          //]]>
        </script>
<?php
    }
  mysql_free_result ($result);
?>
      </div>
      
      <div id="tab2">
        <table cellpadding="0" cellspacing="0">
          <thead>
            <td class="col1"><label>Stylesheet</label></td>
            <td class="col2"><label>Identifier</label></td>
            <td class="col3"><label>Linked</label></td>
            <td class="col3">&nbsp;</td>
          </thead>
<?php
  /* Get all styles */
  $styles = "";
  $result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_styles));
  if (mysql_num_rows ($result) > 0)
    {
      while ($row = mysql_fetch_array ($result))
        $styles[$row['id']] = $row['name'];
    }
  mysql_free_result ($result);

  /* Get related styles */
  $result = mysql_query ("SELECT id, style_id, identifier, linked FROM ".db_maketablename ($table_styles_rel)." WHERE template_id='$tid'");
  if (mysql_num_rows ($result) > 0)
    {
      $stylecount = 1;
      while ($row = mysql_fetch_array ($result))
        {
          print "<tr><td><select name=\"style_name$stylecount\">";
          if ($row['style_id'] == 0)
            print "<option value=\"0\" selected=\"selected\">* SELECT STYLE *</option>";
          foreach ($styles as $key => $style)
            {
              $sel = $key == $row['style_id'] ? " selected=\"selected\"" : "";
              print "<option value=\"$key\"$sel>$style.css</option>";
            }
          print "</select></td>";
          print "<td><input name=\"style_identifier$stylecount\" value=\"".htmlentities ($row['identifier'], ENT_COMPAT, "UTF-8", false)."\" maxlength=\"20\" class=\"smalltextfield\" /></td>";
          print "<td><select name=\"style_linked$stylecount\">";
          print "<option value=\"1\"";
          if ($row['linked'] == 1)
            print " selected=\"selected\"";
          print ">Linked</option>";
          print "<option value=\"0\"";
          if ($row['linked'] == 0)
            print " selected=\"selected\"";
          print ">Inline</option>";
          print "</select></td>";
          print "<td><input type=\"hidden\" name=\"style_id$stylecount\" value=\"{$row['id']}\" /><input type=\"submit\" name=\"delstyle$stylecount\" value=\"-\" class=\"alignright\" /></td>";
          print "</tr>";
          
          $stylecount++;
        }
    }
  mysql_free_result ($result);
?>
        </table>

        <p>
          <input type="submit" name="addstyle" value="+" />
          <span class="addstyle">Add new style</span>
        </p>
      </div>

<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
      <div id="tab1">
<?php
  $result = mysql_query ("SELECT name, xslt FROM ".db_maketablename ($table_sublayouts)." WHERE id='$slid'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      print "<label>Name</label><br /><input type=\"text\" name=\"sublayoutname\" value=\"".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false)."\" class=\"textfield\" />\n";

      $layout = htmlentities ($row['xslt'], ENT_COMPAT, "UTF-8", true);
?>
        <label>Layout</label>
        <textarea id="xslt" name="sublayout"><?=$layout ?></textarea>
        <script type="text/javascript">
          //<![CDATA[
            var editor = CodeMirror.fromTextArea (document.getElementById ("xslt"), { mode: { name: "xmlpure" } });
          //]]>
        </script>
<?php
    }
  mysql_free_result ($result);
?>
      </div>
<?php
}
?>
      <p class="alignright">
        &nbsp;<br />
<?php
if (!empty ($tid) && empty ($slid))
{
?>
        <input type="hidden" name="tid" value="<?=$tid ?>" />
        <input type="hidden" name="fieldcount" value="<?=$fieldcount ?>" />
        <input type="hidden" name="sublayoutcount" value="<?=$sublayoutcount - 1 ?>" />
        <input type="hidden" name="stylecount" value="<?=$stylecount - 1 ?>" />
        <input type="hidden" id="show" name="show" value="<?=isset ($_GET['show']) ? $_GET['show'] : 1; ?>" />
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
        <input type="hidden" name="slid" value="<?=$slid ?>" />
<?php
}
?>
        <input type="submit" value="Save" />
      </p>
    </form>
<?php
}
?>
</div>

<div class="clear"></div>

<script type="text/javascript">
  // <![CDATA[
    switchtabs ('<?=isset ($_GET['show']) ? "tab{$_GET['show']}" : "tab1"; ?>');
  // ]]>
</script>
<?php
}
?>
